package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import cn.com.kh.KHDBConfig

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * DABC对接微信公众号
 *
 */

public class apiWXLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXLogin.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        String dataSourceID = "dataSource";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取嵌入传递的参数
        String opsource = request.getParameter("opsource");
        String opdynid = request.getParameter("opdynid");
        String expand = request.getParameter("expand");

        log.debug("回调参数信息【opsource】：" + opsource + "【opdynid】：" + opdynid + "【expand】：" + expand);

        // NGS Domain信息
        String GroovyOuterURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Outer");
        String redirect_uri = GroovyOuterURL + "/api/apiWXCode?opsource=" + opsource + "&opdynid=" + opdynid + "&expand=" + expand;
        log.debug("预设腾讯验证后重定向地址：" + redirect_uri);
        redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");

        if (opsource == "wxc") {
            // 客户公众号嵌入
            String CustomerURL = KHDBConfig.getAPIURL(eliteBean, "WX-CustomerURL");
            String APPID = KHDBConfig.getParam(eliteBean, "WX1-ID");

            redirect_uri = CustomerURL.replace("#{appid}", APPID).replace("#{redirect_uri}", redirect_uri);

            log.debug("客户公众号嵌入返回重定向URL:" + redirect_uri);

            response.sendRedirect(redirect_uri);

        } else if (opsource == "wxs") {
            // 客户公众号嵌入
            String StaffURL = KHDBConfig.getAPIURL(eliteBean, "WX-StaffURL");
            String APPID = KHDBConfig.getParam(eliteBean, "WX2-ID");

            redirect_uri = StaffURL.replace("#{appid}", APPID).replace("#{redirect_uri}", redirect_uri);

            log.debug("员工公众号嵌入返回重定向URL:" + redirect_uri);

            response.sendRedirect(redirect_uri);

        } else {
            log.warn("未知类型公众号嵌入警告:" + opsource);
            return opsource;
        }
    }

}